//+------------------------------------------------------------------+
//|                                           Amazing5_Improved.mq5 |
//|                                      Converted from Amazing5.0  |
//|                                             Improved for MQ5     |
//+------------------------------------------------------------------+
#property copyright "Amazing5.0 - Improved Version"
#property version   "5.1"
#property description "网格交易EA - 改进版本，具有更好的可读性"

#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\OrderInfo.mqh>

//+------------------------------------------------------------------+
//| 交易相关参数                                                        |
//+------------------------------------------------------------------+
input group "=== 基础交易设置 ==="
input double   StartLotSize = 0.01;            // 起始手数
input double   MaxLotSize = 10.0;              // 最大手数
input double   LotIncrement = 0.0;             // 手数递增值
input double   LotMultiplier = 1.3;            // 手数倍率
input int      LotDecimalPlaces = 2;           // 手数小数位数
input int      MagicNumber = 9453;             // 魔术数字
input int      MaxOrders = 50;                 // 最大订单数量
input int      MaxSpread = 32;                 // 最大点差限制

input group "=== 网格策略参数 ==="
input int      FirstStepDistance = 30;        // 首单距离（点）
input int      GridStepDistance = 100;        // 补单间距（点）
input int      SecondGridStep = 100;          // 第二补单间距（点）
input int      MinGridDistance = 60;          // 最小网格距离（点）
input int      SecondMinDistance = 60;        // 第二最小距离（点）
input int      TrailingStopPoints = 5;        // 挂单追踪点数

input group "=== 价格限制设置 ==="
input double   NoBuyAbovePrice = 0.0;         // 买入价格上限（首单）
input double   NoSellBelowPrice = 0.0;        // 卖出价格下限（首单）
input double   NoBuyAbovePriceGrid = 0.0;     // 买入价格上限（网格）
input double   NoSellBelowPriceGrid = 0.0;    // 卖出价格下限（网格）

input group "=== 时间控制 ==="
input string   TradingStartTime = "00:00";    // 交易开始时间
input string   TradingStopTime = "24:00";     // 交易结束时间
input int      RestartDelaySeconds = 0;       // 平仓后重启延迟（秒）

// 开单模式枚举
enum ENUM_OPENING_MODE
{
    MODE_TIMEZONE = 1,      // 开单时区模式
    MODE_TIME_INTERVAL = 2, // 开单时间间距模式
    MODE_NO_DELAY = 3       // 不延迟模式
};

input group "=== 开单模式设置 ==="
input ENUM_OPENING_MODE OpeningMode = MODE_NO_DELAY;  // 开单模式
input ENUM_TIMEFRAMES   TimeZone = PERIOD_M1;         // 开单时区
input int               OpeningInterval = 30;          // 开单时间间距（秒）

input group "=== 风险管理 ==="
input double   MaxFloatingLoss = 100000.0;    // 单边最大浮亏
input double   CloseAllAtLoss = 50.0;         // 单边平仓限制
input double   CloseAllAtProfit = 0.5;        // 整体平仓金额
input double   SingleSideProfit = 2.0;        // 单边平仓金额
input double   StopLossAmount = 0.0;          // 止损金额
input bool     EnableProfitAccumulation = true; // 单边平仓金额累加
input double   FloatingLossTrigger = 0.0;     // 浮亏触发第二参数

input group "=== 保护策略 ==="
input bool     EnableCounterTrendProtection = true;  // 逆势保护开关
input bool     EnableTrendProtection = true;         // 顺势保护开关
input bool     EnableTrendLocking = false;           // 完全对锁时挂单顺势
input bool     StopAfterClose = false;               // 平仓后停止交易

input group "=== 界面显示 ==="
input bool     ShowControlPanel = true;       // 显示控制面板
input color    PanelColorPositive = Lime;     // 正值颜色
input color    PanelColorNegative = Red;      // 负值颜色
input color    PanelColorNeutral = Blue;      // 中性颜色
input int      FontSize = 10;                 // 字体大小

//+------------------------------------------------------------------+
//| 全局变量 - 使用有意义的命名                                         |
//+------------------------------------------------------------------+
// 交易对象
CTrade         g_Trade;
CPositionInfo  g_Position;
COrderInfo     g_Order;

// 系统状态变量
bool     g_IsInitialized = true;
bool     g_TradingAllowed = true;
int      g_LastTradeDirection = 0;    // 1=买入, -1=卖出, 0=无
int      g_MinDistance = 0;           // 计算后的最小距离
datetime g_LastTradeTime = 0;        // 最后交易时间
datetime g_SessionStartTime = 0;     // 会话开始时间
datetime g_SessionStopTime = 0;      // 会话结束时间

// UI控制变量
string   g_ButtonClose = "ButtonClose";
string   g_ButtonBuy = "ButtonBuy";  
string   g_ButtonSell = "ButtonSell";
string   g_PanelEquity = "PanelEquity";
string   g_PanelSpread = "PanelSpread";

// 价格跟踪变量
double   g_LastAsk = 0.0;
double   g_LastBid = 0.0;
double   g_GridBuyPrice = 0.0;       // 网格买入价格
double   g_GridSellPrice = 0.0;      // 网格卖出价格

// 统计变量
double   g_TotalBuyProfit = 0.0;     // 买单总盈利
double   g_TotalSellProfit = 0.0;    // 卖单总盈利
int      g_BuyOrderCount = 0;        // 买单数量
int      g_SellOrderCount = 0;       // 卖单数量

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
    // 初始化交易对象
    g_Trade.SetExpertMagicNumber(MagicNumber);
    g_Trade.SetDeviationInPoints(30);
    g_Trade.SetTypeFilling(ORDER_FILLING_FOK);
    
    // 计算最小距离
    CalculateMinDistance();
    
    // 验证参数
    if (!ValidateInputParameters())
    {
        Print("输入参数验证失败！");
        return INIT_PARAMETERS_INCORRECT;
    }
    
    // 初始化时间设置
    InitializeTimeSettings();
    
    // 创建界面元素
    if (ShowControlPanel)
    {
        CreateControlPanel();
    }
    
    // 清空注释
    Comment("");
    
    Print("Amazing5 EA 初始化完成");
    return INIT_SUCCEEDED;
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                               |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    // 删除界面对象
    if (ShowControlPanel)
    {
        DeleteControlPanel();
    }
    
    Comment("");
    Print("Amazing5 EA 已停止");
}

//+------------------------------------------------------------------+
//| Expert tick function                                           |
//+------------------------------------------------------------------+
void OnTick()
{
    // 检查交易条件
    if (!IsTradeAllowed())
        return;
        
    // 更新市场信息
    UpdateMarketInfo();
    
    // 更新统计信息
    UpdateStatistics();
    
    // 更新界面显示
    if (ShowControlPanel)
    {
        UpdateControlPanel();
    }
    
    // 执行交易逻辑
    ExecuteTradingLogic();
    
    // 检查风险管理
    CheckRiskManagement();
}

//+------------------------------------------------------------------+
//| Chart event function                                           |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
{
    if (id == CHARTEVENT_OBJECT_CLICK)
    {
        if (sparam == g_ButtonClose)
        {
            CloseAllOrders();
            ObjectSetInteger(0, g_ButtonClose, OBJPROP_STATE, false);
        }
        else if (sparam == g_ButtonBuy)
        {
            // 手动买入逻辑
            ExecuteManualBuy();
            ObjectSetInteger(0, g_ButtonBuy, OBJPROP_STATE, false);
        }
        else if (sparam == g_ButtonSell)
        {
            // 手动卖出逻辑
            ExecuteManualSell();
            ObjectSetInteger(0, g_ButtonSell, OBJPROP_STATE, false);
        }
    }
}

//+------------------------------------------------------------------+
//| 计算最小距离                                                      |
//+------------------------------------------------------------------+
void CalculateMinDistance()
{
    g_MinDistance = (int)MathMax(SymbolInfoInteger(_Symbol, SYMBOL_SPREAD), 
                                SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL)) + 1;
                                
    // 确保各项距离设置不小于最小距离
    if (GridStepDistance < g_MinDistance)
        GridStepDistance = g_MinDistance;
        
    if (FirstStepDistance < g_MinDistance)
        FirstStepDistance = g_MinDistance;
        
    if (MinGridDistance < g_MinDistance)
        MinGridDistance = g_MinDistance;
}

//+------------------------------------------------------------------+
//| 验证输入参数                                                      |
//+------------------------------------------------------------------+
bool ValidateInputParameters()
{
    if (StartLotSize <= 0)
    {
        Print("起始手数必须大于0");
        return false;
    }
    
    if (MaxLotSize < StartLotSize)
    {
        Print("最大手数不能小于起始手数");
        return false;
    }
    
    if (GridStepDistance <= 0)
    {
        Print("网格间距必须大于0");
        return false;
    }
    
    return true;
}

//+------------------------------------------------------------------+
//| 更新市场信息                                                      |
//+------------------------------------------------------------------+
void UpdateMarketInfo()
{
    g_LastAsk = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
    g_LastBid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
}

//+------------------------------------------------------------------+
//| 更新统计信息                                                      |
//+------------------------------------------------------------------+
void UpdateStatistics()
{
    g_TotalBuyProfit = 0.0;
    g_TotalSellProfit = 0.0;
    g_BuyOrderCount = 0;
    g_SellOrderCount = 0;
    
    // 遍历所有持仓
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (g_Position.SelectByIndex(i))
        {
            if (g_Position.Symbol() == _Symbol && g_Position.Magic() == MagicNumber)
            {
                if (g_Position.PositionType() == POSITION_TYPE_BUY)
                {
                    g_BuyOrderCount++;
                    g_TotalBuyProfit += g_Position.Profit() + g_Position.Swap() + g_Position.Commission();
                }
                else if (g_Position.PositionType() == POSITION_TYPE_SELL)
                {
                    g_SellOrderCount++;
                    g_TotalSellProfit += g_Position.Profit() + g_Position.Swap() + g_Position.Commission();
                }
            }
        }
    }
}

//+------------------------------------------------------------------+
//| 统计开放订单数量                                                  |
//+------------------------------------------------------------------+
int CountOpenOrders()
{
    int count = 0;
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (g_Position.SelectByIndex(i))
        {
            if (g_Position.Symbol() == _Symbol && g_Position.Magic() == MagicNumber)
                count++;
        }
    }
    return count;
}

//+------------------------------------------------------------------+
//| 执行交易逻辑 - 基于原始MQ4逻辑重写                             |
//+------------------------------------------------------------------+
void ExecuteTradingLogic()
{
    int totalOrders = CountOpenOrders();
    
    // 检查是否允许交易（原始MQ4中的各种开关检查）
    if (!g_TradingAllowed)
        return;
        
    // 检查Over参数逻辑（平仓后停止交易）
    if (StopAfterClose && totalOrders == 0 && g_LastTradeTime > 0)
    {
        if (RestartDelaySeconds > 0)
        {
            if (TimeCurrent() - g_LastTradeTime < RestartDelaySeconds)
                return;
        }
        else
        {
            // 如果设置了平仓后停止且没有延迟，直接停止
            return;
        }
    }
    
    // 如果没有订单，检查是否可以开首单
    if (totalOrders == 0)
    {
        CheckForFirstOrder();
        return;
    }
    
    // 如果已有订单，检查网格加仓
    if (totalOrders < MaxOrders)
    {
        CheckForGridOrders();
    }
    
    // 检查订单修改（追踪止损等）
    CheckOrderModifications();
}

//+------------------------------------------------------------------+
//| 检查首单开仓条件                                                  |
//+------------------------------------------------------------------+
void CheckForFirstOrder()
{
    // 检查开仓模式
    if (!CheckOpeningMode())
        return;
        
    // 检查价格限制
    bool canBuy = (NoBuyAbovePrice == 0.0 || g_LastAsk <= NoBuyAbovePrice);
    bool canSell = (NoSellBelowPrice == 0.0 || g_LastBid >= NoSellBelowPrice);
    
    // 基于市场条件决定开仓方向
    // 这里可以添加更复杂的信号逻辑
    if (canBuy && ShouldOpenBuy())
    {
        ExecuteBuyOrder(StartLotSize);
    }
    else if (canSell && ShouldOpenSell())
    {
        ExecuteSellOrder(StartLotSize);
    }
}

//+------------------------------------------------------------------+
//| 检查开仓模式                                                      |
//+------------------------------------------------------------------+
bool CheckOpeningMode()
{
    switch(OpeningMode)
    {
        case MODE_TIMEZONE:
            // 基于时区的开仓逻辑
            return CheckTimeZoneCondition();
            
        case MODE_TIME_INTERVAL:
            // 基于时间间隔的开仓逻辑
            return (TimeCurrent() - g_LastTradeTime >= OpeningInterval);
            
        case MODE_NO_DELAY:
        default:
            return true;
    }
}

//+------------------------------------------------------------------+
//| 检查时区条件                                                      |
//+------------------------------------------------------------------+
bool CheckTimeZoneCondition()
{
    // 基于指定时间周期的K线来判断
    static datetime lastBarTime = 0;
    datetime currentBarTime = iTime(_Symbol, TimeZone, 0);
    
    if (currentBarTime != lastBarTime)
    {
        lastBarTime = currentBarTime;
        return true;
    }
    
    return false;
}

//+------------------------------------------------------------------+
//| 判断是否应该买入                                                  |
//+------------------------------------------------------------------+
bool ShouldOpenBuy()
{
    // 检查逆势保护
    if (EnableCounterTrendProtection)
    {
        // 计算买卖双方盈亏差值进行逆势保护
        double buyProfit = CalculateProfitByType(POSITION_TYPE_BUY);
        double sellProfit = CalculateProfitByType(POSITION_TYPE_SELL);
        double profitDiff = buyProfit - sellProfit;
        
        // 如果买单明显盈利且达到一定阈值，不继续买入（逆势保护）
        if (profitDiff > FloatingLossTrigger && buyProfit > 0)
            return false;
    }
    
    // 检查时间窗口
    if (!IsInTradingTime())
        return false;
        
    // 检查价格限制 - 首单
    if (g_BuyOrderCount == 0)
    {
        if (NoBuyAbovePrice > 0 && g_LastAsk > NoBuyAbovePrice)
            return false;
    }
    else
    {
        // 网格单价格限制
        if (NoBuyAbovePriceGrid > 0 && g_LastAsk > NoBuyAbovePriceGrid)
            return false;
    }
    
    // 检查浮亏限制
    if (MaxFloatingLoss > 0 && MathAbs(g_TotalBuyProfit) >= MaxFloatingLoss)
        return false;
        
    // 检查开单模式
    if (!CheckOpeningModeCondition())
        return false;
    
    return true;
}

//+------------------------------------------------------------------+
//| 判断是否应该卖出                                                  |
//+------------------------------------------------------------------+
bool ShouldOpenSell()
{
    // 检查逆势保护
    if (EnableCounterTrendProtection)
    {
        // 计算买卖双方盈亏差值进行逆势保护
        double buyProfit = CalculateProfitByType(POSITION_TYPE_BUY);
        double sellProfit = CalculateProfitByType(POSITION_TYPE_SELL);
        double profitDiff = sellProfit - buyProfit;
        
        // 如果卖单明显盈利且达到一定阈值，不继续卖出（逆势保护）
        if (profitDiff > FloatingLossTrigger && sellProfit > 0)
            return false;
    }
    
    // 检查时间窗口
    if (!IsInTradingTime())
        return false;
        
    // 检查价格限制 - 首单
    if (g_SellOrderCount == 0)
    {
        if (NoSellBelowPrice > 0 && g_LastBid < NoSellBelowPrice)
            return false;
    }
    else
    {
        // 网格单价格限制
        if (NoSellBelowPriceGrid > 0 && g_LastBid < NoSellBelowPriceGrid)
            return false;
    }
    
    // 检查浮亏限制
    if (MaxFloatingLoss > 0 && MathAbs(g_TotalSellProfit) >= MaxFloatingLoss)
        return false;
        
    // 检查开单模式
    if (!CheckOpeningModeCondition())
        return false;
    
    return true;
}

//+------------------------------------------------------------------+
//| 按类型计算盈亏                                                    |
//+------------------------------------------------------------------+
double CalculateProfitByType(ENUM_POSITION_TYPE type)
{
    double totalProfit = 0.0;
    
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (g_Position.SelectByIndex(i))
        {
            if (g_Position.Symbol() == _Symbol && 
                g_Position.Magic() == MagicNumber &&
                g_Position.PositionType() == type)
            {
                totalProfit += g_Position.Profit() + g_Position.Swap() + g_Position.Commission();
            }
        }
    }
    
    return totalProfit;
}

//+------------------------------------------------------------------+
//| 检查是否在交易时间内                                            |
//+------------------------------------------------------------------+
bool IsInTradingTime()
{
    datetime currentTime;
    if (IsTesting())
        currentTime = TimeCurrent();
    else
        currentTime = TimeLocal();
        
    string todayStr = TimeToString(currentTime, TIME_DATE);
    datetime startTime = StringToTime(todayStr + " " + TradingStartTime);
    datetime stopTime = StringToTime(todayStr + " " + TradingStopTime);
    
    // 处理跨日情况
    if (startTime < stopTime)
    {
        return (currentTime >= startTime && currentTime <= stopTime);
    }
    else
    {
        // 跨日交易时间
        return (currentTime >= startTime || currentTime <= stopTime);
    }
}

//+------------------------------------------------------------------+
//| 检查开单模式条件                                                |
//+------------------------------------------------------------------+
bool CheckOpeningModeCondition()
{
    switch(OpeningMode)
    {
        case MODE_TIMEZONE:
            return CheckTimeZoneBasedOpening();
            
        case MODE_TIME_INTERVAL:
            return CheckTimeIntervalBasedOpening();
            
        case MODE_NO_DELAY:
        default:
            return true;
    }
}

//+------------------------------------------------------------------+
//| 检查基于时区的开单条件                                        |
//+------------------------------------------------------------------+
bool CheckTimeZoneBasedOpening()
{
    static datetime lastBarTime = 0;
    datetime currentBarTime = iTime(_Symbol, TimeZone, 0);
    
    if (currentBarTime != lastBarTime)
    {
        lastBarTime = currentBarTime;
        return true;
    }
    
    return false;
}

//+------------------------------------------------------------------+
//| 检查基于时间间隔的开单条件                                  |
//+------------------------------------------------------------------+
bool CheckTimeIntervalBasedOpening()
{
    if (g_LastTradeTime == 0)
        return true;
        
    return (TimeCurrent() - g_LastTradeTime >= OpeningInterval);
}

//+------------------------------------------------------------------+
//| 检查网格加仓                                                      |
//+------------------------------------------------------------------+
void CheckForGridOrders()
{
    // 检查买单网格加仓
    if (ShouldOpenBuy())
    {
        double lastBuyPrice = GetLastOrderPrice(POSITION_TYPE_BUY);
        
        // 如果没有买单，尝试开首单
        if (lastBuyPrice == 0)
        {
            ExecuteBuyOrder(StartLotSize);
        }
        else
        {
            // 检查是否需要加仓
            double gridDistance = (g_BuyOrderCount == 1) ? FirstStepDistance * _Point : GridStepDistance * _Point;
            if (g_LastAsk <= lastBuyPrice - gridDistance)
            {
                double lotSize = CalculateNextLotSize(POSITION_TYPE_BUY);
                if (lotSize <= MaxLotSize && g_BuyOrderCount < MaxOrders)
                {
                    ExecuteBuyOrder(lotSize);
                }
            }
        }
    }
    
    // 检查卖单网格加仓
    if (ShouldOpenSell())
    {
        double lastSellPrice = GetLastOrderPrice(POSITION_TYPE_SELL);
        
        // 如果没有卖单，尝试开首单
        if (lastSellPrice == 0)
        {
            ExecuteSellOrder(StartLotSize);
        }
        else
        {
            // 检查是否需要加仓
            double gridDistance = (g_SellOrderCount == 1) ? FirstStepDistance * _Point : GridStepDistance * _Point;
            if (g_LastBid >= lastSellPrice + gridDistance)
            {
                double lotSize = CalculateNextLotSize(POSITION_TYPE_SELL);
                if (lotSize <= MaxLotSize && g_SellOrderCount < MaxOrders)
                {
                    ExecuteSellOrder(lotSize);
                }
            }
        }
    }
}

//+------------------------------------------------------------------+
//| 获取最后订单价格                                                  |
//+------------------------------------------------------------------+
double GetLastOrderPrice(ENUM_POSITION_TYPE type)
{
    double lastPrice = 0.0;
    datetime lastTime = 0;
    
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (g_Position.SelectByIndex(i))
        {
            if (g_Position.Symbol() == _Symbol && 
                g_Position.Magic() == MagicNumber &&
                g_Position.PositionType() == type)
            {
                if (g_Position.Time() > lastTime)
                {
                    lastTime = g_Position.Time();
                    lastPrice = g_Position.PriceOpen();
                }
            }
        }
    }
    
    return lastPrice;
}

//+------------------------------------------------------------------+
//| 计算下一手手数                                                    |
//+------------------------------------------------------------------+
double CalculateNextLotSize(ENUM_POSITION_TYPE type)
{
    int orderCount = (type == POSITION_TYPE_BUY) ? g_BuyOrderCount : g_SellOrderCount;
    
    double nextLot = StartLotSize;
    
    if (LotIncrement > 0)
    {
        nextLot = StartLotSize + (orderCount * LotIncrement);
    }
    else if (LotMultiplier > 1.0)
    {
        nextLot = StartLotSize * MathPow(LotMultiplier, orderCount);
    }
    
    // 规范化手数
    double lotStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
    nextLot = NormalizeDouble(nextLot / lotStep, 0) * lotStep;
    
    // 确保在允许范围内
    double minLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
    double maxLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
    
    nextLot = MathMin(MathMax(nextLot, minLot), maxLot);
    nextLot = MathMin(nextLot, MaxLotSize);
    
    return nextLot;
}

//+------------------------------------------------------------------+
//| 执行买入订单                                                      |
//+------------------------------------------------------------------+
bool ExecuteBuyOrder(double lotSize)
{
    double price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
    double sl = 0.0; // 止损价格，可根据策略设置
    double tp = 0.0; // 止盈价格，可根据策略设置
    
    string comment = StringFormat("Grid Buy #%d", g_BuyOrderCount + 1);
    
    if (g_Trade.Buy(lotSize, _Symbol, price, sl, tp, comment))
    {
        g_LastTradeTime = TimeCurrent();
        g_LastTradeDirection = 1;
        Print(StringFormat("买入订单成功: 手数=%.2f, 价格=%.5f", lotSize, price));
        return true;
    }
    else
    {
        Print("买入订单失败: ", g_Trade.ResultRetcodeDescription());
        return false;
    }
}

//+------------------------------------------------------------------+
//| 执行卖出订单                                                      |
//+------------------------------------------------------------------+
bool ExecuteSellOrder(double lotSize)
{
    double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    double sl = 0.0; // 止损价格，可根据策略设置
    double tp = 0.0; // 止盈价格，可根据策略设置
    
    string comment = StringFormat("Grid Sell #%d", g_SellOrderCount + 1);
    
    if (g_Trade.Sell(lotSize, _Symbol, price, sl, tp, comment))
    {
        g_LastTradeTime = TimeCurrent();
        g_LastTradeDirection = -1;
        Print(StringFormat("卖出订单成功: 手数=%.2f, 价格=%.5f", lotSize, price));
        return true;
    }
    else
    {
        Print("卖出订单失败: ", g_Trade.ResultRetcodeDescription());
        return false;
    }
}

//+------------------------------------------------------------------+
//| 检查订单修改                                                      |
//+------------------------------------------------------------------+
void CheckOrderModifications()
{
    if (TrailingStopPoints <= 0)
        return;
        
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (g_Position.SelectByIndex(i))
        {
            if (g_Position.Symbol() == _Symbol && g_Position.Magic() == MagicNumber)
            {
                ModifyTrailingStop();
            }
        }
    }
}

//+------------------------------------------------------------------+
//| 修改追踪止损                                                      |
//+------------------------------------------------------------------+
void ModifyTrailingStop()
{
    double openPrice = g_Position.PriceOpen();
    double currentSL = g_Position.StopLoss();
    double currentTP = g_Position.TakeProfit();
    double newSL = 0.0;
    
    if (g_Position.PositionType() == POSITION_TYPE_BUY)
    {
        double newStopLevel = g_LastBid - (TrailingStopPoints * _Point);
        if (currentSL == 0.0 || newStopLevel > currentSL)
        {
            newSL = newStopLevel;
        }
    }
    else if (g_Position.PositionType() == POSITION_TYPE_SELL)
    {
        double newStopLevel = g_LastAsk + (TrailingStopPoints * _Point);
        if (currentSL == 0.0 || newStopLevel < currentSL)
        {
            newSL = newStopLevel;
        }
    }
    
    if (newSL > 0.0 && MathAbs(newSL - currentSL) > _Point)
    {
        g_Trade.PositionModify(g_Position.Ticket(), newSL, currentTP);
    }
}

//+------------------------------------------------------------------+
//| 检查风险管理 - 基于原始MQ4逻辑                                   |
//+------------------------------------------------------------------+
void CheckRiskManagement()
{
    double totalProfit = g_TotalBuyProfit + g_TotalSellProfit;
    
    // 检查平仓后停止交易逻辑
    if (StopAfterClose && CountOpenOrders() == 0)
    {
        if (RestartDelaySeconds > 0 && g_LastTradeTime > 0)
        {
            if (TimeCurrent() - g_LastTradeTime < RestartDelaySeconds)
            {
                Comment("平仓后等待重启，剩余: " + 
                        IntegerToString(RestartDelaySeconds - (TimeCurrent() - g_LastTradeTime)) + "秒");
                return;
            }
        }
    }
    
    // 检查整体平仓条件（原始MQ4中的CloseAll逻辑）
    if (CloseAllAtProfit > 0 && totalProfit >= CloseAllAtProfit)
    {
        CloseAllOrders();
        Print("达到整体盈利目标: ", DoubleToString(totalProfit, 2), ", 全部平仓");
        return;
    }
    
    // 检查整体止损条件
    if (StopLossAmount > 0 && totalProfit <= -StopLossAmount)
    {
        CloseAllOrders();
        Print("达到止损目标: ", DoubleToString(totalProfit, 2), ", 全部平仓");
        return;
    }
    
    // 检查单边平仓条件（单边盈利或亏损达到阈值）
    bool buyProfitTriggered = false;
    bool sellProfitTriggered = false;
    
    // 买单平仓条件
    if (SingleSideProfit > 0)
    {
        double buyTarget = EnableProfitAccumulation ? (SingleSideProfit * g_BuyOrderCount) : SingleSideProfit;
        if (g_TotalBuyProfit >= buyTarget)
        {
            CloseBuyOrders();
            buyProfitTriggered = true;
            Print("买单达到盈利目标: ", DoubleToString(g_TotalBuyProfit, 2));
        }
    }
    
    // 卖单平仓条件
    if (SingleSideProfit > 0)
    {
        double sellTarget = EnableProfitAccumulation ? (SingleSideProfit * g_SellOrderCount) : SingleSideProfit;
        if (g_TotalSellProfit >= sellTarget)
        {
            CloseSellOrders();
            sellProfitTriggered = true;
            Print("卖单达到盈利目标: ", DoubleToString(g_TotalSellProfit, 2));
        }
    }
    
    // 检查单边亏损限制
    if (CloseAllAtLoss > 0)
    {
        if (g_TotalBuyProfit <= -CloseAllAtLoss)
        {
            CloseBuyOrders();
            Print("买单亏损超限: ", DoubleToString(g_TotalBuyProfit, 2), ", 平仓");
        }
        
        if (g_TotalSellProfit <= -CloseAllAtLoss)
        {
            CloseSellOrders();
            Print("卖单亏损超限: ", DoubleToString(g_TotalSellProfit, 2), ", 平仓");
        }
    }
    
    // 检查逆势和顺势保护逻辑（原始MQ4中的CloseBuySell和HomeopathyCloseAll）
    if (EnableCounterTrendProtection)
    {
        CheckCounterTrendProtection();
    }
    
    if (EnableTrendProtection)
    {
        CheckTrendProtection();
    }
}

//+------------------------------------------------------------------+
//| 检查逆势保护（原始MQ4中的CloseBuySell逻辑）                    |
//+------------------------------------------------------------------+
void CheckCounterTrendProtection()
{
    // 基于原始MQ4代码中的逆势保护逻辑
    // 当一个方向盈利时，可能需要平掉反向交易
    
    double buyProfit = g_TotalBuyProfit;
    double sellProfit = g_TotalSellProfit;
    double profitDiff = MathAbs(buyProfit - sellProfit);
    
    // 如果一个方向明显盈利，而另一个方向亏损且差距超过阈值
    if (profitDiff > FloatingLossTrigger && FloatingLossTrigger > 0)
    {
        if (buyProfit > sellProfit + FloatingLossTrigger)
        {
            // 买单盈利明显，平掉亏损的卖单
            if (sellProfit < 0)
            {
                CloseSellOrders();
                Print("逆势保护: 平掉亏损卖单");
            }
        }
        else if (sellProfit > buyProfit + FloatingLossTrigger)
        {
            // 卖单盈利明显，平掉亏损的买单
            if (buyProfit < 0)
            {
                CloseBuyOrders();
                Print("逆势保护: 平掉亏损买单");
            }
        }
    }
}

//+------------------------------------------------------------------+
//| 检查顺势保护（原始MQ4中的HomeopathyCloseAll逻辑）             |
//+------------------------------------------------------------------+
void CheckTrendProtection()
{
    // 顺势保护逻辑 - 当双方都盈利时可能一起平仓
    if (g_TotalBuyProfit > 0 && g_TotalSellProfit > 0)
    {
        double totalProfit = g_TotalBuyProfit + g_TotalSellProfit;
        if (totalProfit >= CloseAllAtProfit && CloseAllAtProfit > 0)
        {
            CloseAllOrders();
            Print("顺势保护: 双方盈利，全部平仓");
        }
    }
}

//+------------------------------------------------------------------+
//| 检查首单开仓条件 - 重写以符合原始MQ4逻辑                     |
//+------------------------------------------------------------------+
void CheckForFirstOrder()
{
    // 检查是否在交易时间内
    if (!IsInTradingTime())
        return;
        
    // 检查开单模式
    if (!CheckOpeningModeCondition())
        return;
    
    // 检查是否有足够的资金
    double requiredMargin = SymbolInfoDouble(_Symbol, SYMBOL_MARGIN_INITIAL) * StartLotSize;
    if (AccountInfoDouble(ACCOUNT_MARGIN_FREE) < requiredMargin)
    {
        Comment("保证金不足，无法开单");
        return;
    }
    
    // 尝试开买单（首单）
    if (ShouldOpenBuy() && g_BuyOrderCount == 0)
    {
        ExecuteBuyOrder(StartLotSize);
        return;
    }
    
    // 尝试开卖单（首单）
    if (ShouldOpenSell() && g_SellOrderCount == 0)
    {
        ExecuteSellOrder(StartLotSize);
        return;
    }
}

//+------------------------------------------------------------------+
//| 平掉所有买单                                                      |
//+------------------------------------------------------------------+
void CloseBuyOrders()
{
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (g_Position.SelectByIndex(i))
        {
            if (g_Position.Symbol() == _Symbol && 
                g_Position.Magic() == MagicNumber &&
                g_Position.PositionType() == POSITION_TYPE_BUY)
            {
                g_Trade.PositionClose(g_Position.Ticket());
            }
        }
    }
}

//+------------------------------------------------------------------+
//| 平掉所有卖单                                                      |
//+------------------------------------------------------------------+
void CloseSellOrders()
{
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (g_Position.SelectByIndex(i))
        {
            if (g_Position.Symbol() == _Symbol && 
                g_Position.Magic() == MagicNumber &&
                g_Position.PositionType() == POSITION_TYPE_SELL)
            {
                g_Trade.PositionClose(g_Position.Ticket());
            }
        }
    }
}

//+------------------------------------------------------------------+
//| 平掉所有订单                                                      |
//+------------------------------------------------------------------+
void CloseAllOrders()
{
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (g_Position.SelectByIndex(i))
        {
            if (g_Position.Symbol() == _Symbol && g_Position.Magic() == MagicNumber)
            {
                g_Trade.PositionClose(g_Position.Ticket());
            }
        }
    }
    
    g_LastTradeTime = TimeCurrent();
    Print("所有订单已平仓");
}

//+------------------------------------------------------------------+
//| 手动买入                                                        |
//+------------------------------------------------------------------+
void ExecuteManualBuy()
{
    if (IsTradeAllowed())
    {
        double lotSize = CalculateNextLotSize(POSITION_TYPE_BUY);
        if (lotSize <= MaxLotSize)
        {
            ExecuteBuyOrder(lotSize);
        }
        else
        {
            Comment("手数超限，无法开仓");
        }
    }
}

//+------------------------------------------------------------------+
//| 手动卖出                                                        |
//+------------------------------------------------------------------+
void ExecuteManualSell()
{
    if (IsTradeAllowed())
    {
        double lotSize = CalculateNextLotSize(POSITION_TYPE_SELL);
        if (lotSize <= MaxLotSize)
        {
            ExecuteSellOrder(lotSize);
        }
        else
        {
            Comment("手数超限，无法开仓");
        }
    }
}

//+------------------------------------------------------------------+
//| 创建控制面板                                                    |
//+------------------------------------------------------------------+
void CreateControlPanel()
{
    int yOffset = 30;
    int buttonWidth = 80;
    int buttonHeight = 25;
    
    // 平仓按钮
    ObjectCreate(0, g_ButtonClose, OBJ_BUTTON, 0, 0, 0);
    ObjectSetInteger(0, g_ButtonClose, OBJPROP_CORNER, CORNER_RIGHT_UPPER);
    ObjectSetInteger(0, g_ButtonClose, OBJPROP_XDISTANCE, 10);
    ObjectSetInteger(0, g_ButtonClose, OBJPROP_YDISTANCE, yOffset);
    ObjectSetInteger(0, g_ButtonClose, OBJPROP_XSIZE, buttonWidth);
    ObjectSetInteger(0, g_ButtonClose, OBJPROP_YSIZE, buttonHeight);
    ObjectSetString(0, g_ButtonClose, OBJPROP_TEXT, "全部平仓");
    ObjectSetInteger(0, g_ButtonClose, OBJPROP_COLOR, White);
    ObjectSetInteger(0, g_ButtonClose, OBJPROP_BGCOLOR, Red);
    ObjectSetInteger(0, g_ButtonClose, OBJPROP_FONTSIZE, FontSize);
    
    yOffset += buttonHeight + 5;
    
    // 买入按钮
    ObjectCreate(0, g_ButtonBuy, OBJ_BUTTON, 0, 0, 0);
    ObjectSetInteger(0, g_ButtonBuy, OBJPROP_CORNER, CORNER_RIGHT_UPPER);
    ObjectSetInteger(0, g_ButtonBuy, OBJPROP_XDISTANCE, 10);
    ObjectSetInteger(0, g_ButtonBuy, OBJPROP_YDISTANCE, yOffset);
    ObjectSetInteger(0, g_ButtonBuy, OBJPROP_XSIZE, buttonWidth);
    ObjectSetInteger(0, g_ButtonBuy, OBJPROP_YSIZE, buttonHeight);
    ObjectSetString(0, g_ButtonBuy, OBJPROP_TEXT, "手动买入");
    ObjectSetInteger(0, g_ButtonBuy, OBJPROP_COLOR, White);
    ObjectSetInteger(0, g_ButtonBuy, OBJPROP_BGCOLOR, PanelColorPositive);
    ObjectSetInteger(0, g_ButtonBuy, OBJPROP_FONTSIZE, FontSize);
    
    yOffset += buttonHeight + 5;
    
    // 卖出按钮
    ObjectCreate(0, g_ButtonSell, OBJ_BUTTON, 0, 0, 0);
    ObjectSetInteger(0, g_ButtonSell, OBJPROP_CORNER, CORNER_RIGHT_UPPER);
    ObjectSetInteger(0, g_ButtonSell, OBJPROP_XDISTANCE, 10);
    ObjectSetInteger(0, g_ButtonSell, OBJPROP_YDISTANCE, yOffset);
    ObjectSetInteger(0, g_ButtonSell, OBJPROP_XSIZE, buttonWidth);
    ObjectSetInteger(0, g_ButtonSell, OBJPROP_YSIZE, buttonHeight);
    ObjectSetString(0, g_ButtonSell, OBJPROP_TEXT, "手动卖出");
    ObjectSetInteger(0, g_ButtonSell, OBJPROP_COLOR, White);
    ObjectSetInteger(0, g_ButtonSell, OBJPROP_BGCOLOR, PanelColorNegative);
    ObjectSetInteger(0, g_ButtonSell, OBJPROP_FONTSIZE, FontSize);
    
    yOffset += buttonHeight + 10;
    
    // 净值显示
    ObjectCreate(0, g_PanelEquity, OBJ_LABEL, 0, 0, 0);
    ObjectSetInteger(0, g_PanelEquity, OBJPROP_CORNER, CORNER_RIGHT_UPPER);
    ObjectSetInteger(0, g_PanelEquity, OBJPROP_XDISTANCE, 10);
    ObjectSetInteger(0, g_PanelEquity, OBJPROP_YDISTANCE, yOffset);
    ObjectSetString(0, g_PanelEquity, OBJPROP_TEXT, "净值: 0.00");
    ObjectSetInteger(0, g_PanelEquity, OBJPROP_COLOR, PanelColorNeutral);
    ObjectSetInteger(0, g_PanelEquity, OBJPROP_FONTSIZE, FontSize);
    ObjectSetString(0, g_PanelEquity, OBJPROP_FONT, "Arial");
    
    yOffset += 20;
    
    // 点差显示
    ObjectCreate(0, g_PanelSpread, OBJ_LABEL, 0, 0, 0);
    ObjectSetInteger(0, g_PanelSpread, OBJPROP_CORNER, CORNER_RIGHT_UPPER);
    ObjectSetInteger(0, g_PanelSpread, OBJPROP_XDISTANCE, 10);
    ObjectSetInteger(0, g_PanelSpread, OBJPROP_YDISTANCE, yOffset);
    ObjectSetString(0, g_PanelSpread, OBJPROP_TEXT, "点差: 0");
    ObjectSetInteger(0, g_PanelSpread, OBJPROP_COLOR, PanelColorNeutral);
    ObjectSetInteger(0, g_PanelSpread, OBJPROP_FONTSIZE, FontSize);
    ObjectSetString(0, g_PanelSpread, OBJPROP_FONT, "Arial");
}

//+------------------------------------------------------------------+
//| 更新控制面板                                                    |
//+------------------------------------------------------------------+
void UpdateControlPanel()
{
    // 更新净值显示
    double equity = AccountInfoDouble(ACCOUNT_EQUITY);
    string equityText = StringFormat("净值: %.2f", equity);
    ObjectSetString(0, g_PanelEquity, OBJPROP_TEXT, equityText);
    
    // 更新点差显示
    int spread = (int)SymbolInfoInteger(_Symbol, SYMBOL_SPREAD);
    string spreadText = StringFormat("点差: %d", spread);
    ObjectSetString(0, g_PanelSpread, OBJPROP_TEXT, spreadText);
    
    // 根据点差设置颜色
    color spreadColor = (spread <= MaxSpread) ? PanelColorPositive : PanelColorNegative;
    ObjectSetInteger(0, g_PanelSpread, OBJPROP_COLOR, spreadColor);
    
    // 更新注释信息
    UpdateCommentInfo();
}

//+------------------------------------------------------------------+
//| 更新注释信息 - 基于原始MQ4的显示风格                           |
//+------------------------------------------------------------------+
void UpdateCommentInfo()
{
    string info = "";
    double totalProfit = g_TotalBuyProfit + g_TotalSellProfit;
    double spread = (SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SymbolInfoDouble(_Symbol, SYMBOL_BID)) / _Point;
    
    // 主要信息显示
    info += "Amazing5 EA - 网格交易\n";
    info += StringFormat("时间: %s\n", TimeToString(TimeCurrent(), TIME_SECONDS));
    info += StringFormat("点差: %.1f pips\n", spread);
    info += StringFormat("杠杆: %.0f倍\n", AccountInfoInteger(ACCOUNT_LEVERAGE));
    info += "\n";
    
    // 交易统计信息
    info += StringFormat("买单: %d 手 (%.2f)\n", g_BuyOrderCount, g_TotalBuyProfit);
    info += StringFormat("卖单: %d 手 (%.2f)\n", g_SellOrderCount, g_TotalSellProfit);
    info += StringFormat("总盈亏: %.2f\n", totalProfit);
    info += "\n";
    
    // 账户信息
    info += StringFormat("余额: %.2f\n", AccountInfoDouble(ACCOUNT_BALANCE));
    info += StringFormat("净值: %.2f\n", AccountInfoDouble(ACCOUNT_EQUITY));
    info += StringFormat("可用保证金: %.2f\n", AccountInfoDouble(ACCOUNT_MARGIN_FREE));
    
    // 状态信息
    if (!IsTradeAllowed())
    {
        info += "\n状态: 交易停止";
        if (!IsInTradingTime())
            info += " (非交易时间)";
    }
    else
    {
        info += "\n状态: 交易中";
    }
    
    Comment(info);
}

//+------------------------------------------------------------------+
//| 删除控制面板                                                    |
//+------------------------------------------------------------------+
void DeleteControlPanel()
{
    ObjectDelete(0, g_ButtonClose);
    ObjectDelete(0, g_ButtonBuy);
    ObjectDelete(0, g_ButtonSell);
    ObjectDelete(0, g_PanelEquity);
    ObjectDelete(0, g_PanelSpread);
}

//+------------------------------------------------------------------+
//| 获取EA状态信息                                                  |
//+------------------------------------------------------------------+
string GetEAStatusInfo()
{
    string status = "EA状态: ";
    
    if (!IsTradeAllowed())
        status += "交易停止 - ";
    else
        status += "交易中 - ";
        
    if (TimeCurrent() < g_SessionStartTime || TimeCurrent() > g_SessionStopTime)
        status += "非交易时间";
    else
        status += "交易时间";
        
    return status;
}
}

//+------------------------------------------------------------------+
//| 初始化时间设置                                                    |
//+------------------------------------------------------------------+
void InitializeTimeSettings()
{
    // 处理时间字符串，移除空格
    string startTime = TradingStartTime;
    string stopTime = TradingStopTime;
    
    StringReplace(startTime, " ", "");
    StringReplace(stopTime, " ", "");
    
    // 特殊处理24:00
    if (stopTime == "24:00")
        stopTime = "23:59:59";
        
    // 构造完整的时间
    g_SessionStartTime = StringToTime(StringConcatenate(TimeToString(TimeCurrent(), TIME_DATE), " ", startTime));
    g_SessionStopTime = StringToTime(StringConcatenate(TimeToString(TimeCurrent(), TIME_DATE), " ", stopTime));
}

//+------------------------------------------------------------------+
//| 检查是否允许交易 - 基于原始MQ4逻辑                                |
//+------------------------------------------------------------------+
bool IsTradeAllowed()
{
    // 检查EA名称（原始MQ4中的验证逻辑）
    if (WindowExpertName() != "Amazing5_Improved")
    {
        Comment("验证失败，EA已停止工作");
        return false;
    }
    
    // 检查点差限制
    int currentSpread = (int)SymbolInfoInteger(_Symbol, SYMBOL_SPREAD);
    if (currentSpread > MaxSpread)
    {
        Comment(StringFormat("点差过大: %d > %d", currentSpread, MaxSpread));
        return false;
    }
    
    // 检查交易时间窗口
    if (!IsInTradingTime())
    {
        return false;
    }
    
    // 检查账户保证金
    double freeMargin = AccountInfoDouble(ACCOUNT_MARGIN_FREE);
    double minMargin = SymbolInfoDouble(_Symbol, SYMBOL_MARGIN_INITIAL) * StartLotSize;
    if (freeMargin < minMargin)
    {
        Comment("保证金不足");
        return false;
    }
    
    // 检查交易环境
    if (!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))
    {
        Comment("终端不允许交易");
        return false;
    }
    
    if (!MQLInfoInteger(MQL_TRADE_ALLOWED))
    {
        Comment("程序不允许交易");
        return false;
    }
    
    return true;
}